const { think } = require('thinkjs');
const Base = require('./base.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.post('page') || 1;
    const size = this.post('size') || 20;
    const query = {};

    if (this.post('searchKey')) {
      query.name = ['like', `%${this.post('searchKey')}%`];
      this.model('user_search').thenUpdate(
        {
          user_id: this.getLoginUserId(),
          key: this.post('searchKey'),
          create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        },
        {
          user_id: this.getLoginUserId(),
          key: this.post('searchKey'),
        }
      );
    }
    if (this.post('job_type')) {
      query.type = ['IN', [this.post('job_type'), 0]];
    }
    if (this.post('job_cate')) {
      // query.cate_last = ['IN', this.post('job_cate').concat([null])];
      query.cate_id = this.post('job_cate');
    }
    if (this.post('city') && this.post('city').length) {
      const companyCity = await this.model('company_job')
        .where({
          city_code: ['IN', this.post('city')],
        })
        .getField('job_id');
      if (think.isEmpty(companyCity)) {
        return this.success({ data: [] });
      } else {
        query.id = ['IN', companyCity];
      }
    }

    let order;
    if (this.post('type') === 1) {
      order = ['id DESC'];
    } else if (this.post('type') === 2) {
      order = ['id DESC'];
    } else if (this.post('type') === 3) {
      const f = await this.model('job').index(
        this.post('lon'),
        this.post('lat'),
        page,
        size
      );
      return this.success({
        data: f,
      });
    }

    query.status = 1;

    const userJobs = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .getField('jobs', true);

    query.id = ['IN', userJobs || ''];

    const data = await this.model('post_list')
      .order(order)
      .where(query)
      .page(page, size)
      .countSelect();

    data.data = await this.model('index').getJobInfo(data.data);

    return this.success(data);
  }
};
